package com.wang.myblog.service.impl;

import com.wang.myblog.entity.Statistics;
import com.wang.myblog.mapper.StatisticsMapper;
import com.wang.myblog.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private StatisticsMapper statisticsMapper;

    @Override
    @Transactional
    public boolean add(Date date) {
        Date date1=null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            date1=sdf.parse(sdf.format(date));
        }catch (ParseException e){
            e.printStackTrace();
        }
        if(statisticsMapper.queryByDate(date1)!=null){
            statisticsMapper.addCount(date1);
        }else {
            Statistics statistics=new Statistics(date1,1);
            statisticsMapper.insert(statistics);
        }
        return true;
    }

    @Override
    public List<Statistics> queryAll() {
        return statisticsMapper.queryAll();
    }

    @Override
    public List<Statistics> getRecentRequests() {
        return statisticsMapper.getRecentRequests();
    }

    @Override
    public String getRecentRequestsDate() {
        String[] dateList=new String[10];
        SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
//        List<String> list=new ArrayList<>();
        List<Statistics> statisticsList=statisticsMapper.getRecentRequests();
        for (int i=0;i<statisticsList.size();i++){
            dateList[9-i]=sdf.format(statisticsList.get(i).getDate());
        }
        String result="[";
        for (int k=0;k<dateList.length;k++){
            result += '"'+dateList[k]+'"'+",";
        }

        return result+"]";
    }

    @Override
    public String getRecentRequestsCounts() {
        Integer[] counts=new Integer[10];
        List<Statistics> statisticsList=statisticsMapper.getRecentRequests();
        for (int i=0;i<statisticsList.size();i++){
            counts[i]=statisticsList.get(i).getRequestCount();
        }
        return Arrays.toString(counts);
    }

    @Override
    public Map<String, Integer> getRequestCount() {
        Map<String,Integer> map=new HashMap<>();
        map.put("week",statisticsMapper.getRequestCount(7));
        map.put("month",statisticsMapper.getRequestCount(30));
        map.put("year",statisticsMapper.getRequestCount(365));
        map.put("total",statisticsMapper.getRequestCount(-1));
        return map;
    }
}
